package cn.wubo.file.preview.demo;

import cn.wubo.file.preview.core.FilePreviewInfo;
import cn.wubo.file.preview.core.FilePreviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(value = "/page")
public class PageController {

    @Autowired
    FilePreviewService filePreviewService;

    @PostMapping(value = "/upload")
    public void upload(MultipartFile file, HttpServletRequest req, HttpServletResponse resp) {
        if (!file.isEmpty()) {
            try {
                FilePreviewInfo filePreviewInfo = filePreviewService.covert(file.getInputStream(), file.getOriginalFilename());
                resp.sendRedirect(req.getContextPath() + "/page/upload?isSuccess=true");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                resp.sendRedirect(req.getContextPath() + "/page/upload?isSuccess=false");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @GetMapping(value = "/upload")
    public String upload(Model model, @RequestParam(required = false) String isSuccess) {
        if (StringUtils.hasLength(isSuccess) && "true".equals(isSuccess)) {
            model.addAttribute("isSuccess", isSuccess);
            model.addAttribute("message", "上传成功！请试试预览文件吧！");
        } else if (StringUtils.hasLength(isSuccess)) {
            model.addAttribute("isSuccess", isSuccess);
            model.addAttribute("message", "上传失败！");
        }
        return "upload";
    }
}
